package net.masker.bbtweet;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.io.http.HttpProtocolConstants;

class StatusUpdater extends Thread
{
	Properties properties = Properties.fetch();
	private static String updateURL = "http://twitter.com/statuses/update.xml";
	private HttpConnection sendConn;
	
	public void run()
	{
		// Fetch a new copy of properties
		properties = Properties.fetch();
		
		// Return if nothing to do
    	if (properties.getPushStatusUpdate() != 1)
    		return;
    	
    	// Make user specified # of attempts to deliver message
    	for (int i = properties.getStatusUpdateRetryAttempts(); i > 0; --i)
    	{	
    		// break if canceled by user
    		if (Properties.fetch().getPushStatusUpdate() == 4)
    			break;
    		
    		try
			{
				// Create post data
				URLEncodedPostData post = new URLEncodedPostData("", false);
				post.append("source", "bbtweet");
				post.append("status", properties.getStatusUpdate());
				StreamConnection s = (StreamConnection)Connector.open(updateURL + "?" + post.toString(), Connector.READ_WRITE, true);
				sendConn = (HttpConnection)s;
	            sendConn.setRequestProperty(HttpProtocolConstants.HEADER_AUTHORIZATION,"Basic "
	            		+ properties.getAuthenticationHash());
	            sendConn.setRequestMethod("POST");
	            
	            // Connect and check status
	            int status = sendConn.getResponseCode();
	            if (status != HttpConnection.HTTP_OK)
	            {
	            	// Log failure and continue
	            	properties = Properties.fetch();
                	properties.setBbtweetStatusMessage("Update: " + sendConn.getResponseMessage());
                	properties.save();
	            	continue;
	            }
	            else
	            {
	    			// Log success, update status, and return
	            	properties = Properties.fetch();
	            	properties.setBbtweetStatusMessage("Update: HTTP_OK 200");
	            	properties.setPushStatusUpdate(2);
	            	properties.save();
	            	return;
	            }
	            
			}
			catch (IOException e) 
	        {
	        	// Log IO Exception
				properties = Properties.fetch();
	        	properties.setBbtweetStatusMessage("Update: " + e.toString());
	        	properties.save();
	        }
    	}
    	
    	// Retry attempts exhausted, update status and return
    	properties = Properties.fetch();
    	properties.setPushStatusUpdate(3);
    	properties.save();
    	return;
	}
	
	public void stopSend()
	{
		try
		{
			sendConn.close();
		}
		catch (IOException e)
		{
			// Ignore exception
		}
	}
}